package com.dsz.du.mealbooking.contoller;

import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.dsz.du.mealbooking.commands.LoginCommand;
import com.dsz.du.mealbooking.commands.RegisterCommand;
import com.dsz.du.mealbooking.exceptions.UserHasExistException;
import com.dsz.du.mealbooking.model.MealModel;
import com.dsz.du.mealbooking.model.UserModel;
import com.dsz.du.mealbooking.services.UserService;
import com.dsz.du.mealbooking.services.BookMealServices;

/**
 * 用户操作 控制器
 * Login
 * Logout
 * Register
 * Modify
 * @author du
 *
 */
@Controller
public class ManagementController {

	public ManagementController() {}
	
	private static Logger logger = Logger.getLogger(ManagementController.class);
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private BookMealServices bookMealServices;
	
	@Autowired
	@Qualifier("userValidator")
	private Validator userValidator;
	
	public void setUserValidator(Validator userValidator) {
		this.userValidator = userValidator;
	}

	/**
	 * Login 登陆
	 * @param model
	 * @param user
	 * @param bindingResult
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/11login.do", method = RequestMethod.POST)  
	protected String login(ModelMap model, @ModelAttribute("user") LoginCommand user,BindingResult bindingResult) throws Exception {
		
		String result = "login";
		String userId = user.getUserId();
		String password = user.getPassword();
		if (logger.isDebugEnabled()) {
			logger.debug(" userId is : " + userId);
			logger.debug(" password is : " + password);
		}
		
		userValidator.validate(user, bindingResult);
		
		if (bindingResult.hasErrors()) {
			return "login";
		}
		
		if (userService.authenticate(user)){
			List<MealModel> meals = bookMealServices.getOrder(userId);
			model.addAttribute("meals",meals);
			if ("admin".equals(userId)){
				result = "manage/managePage";
			} else {
				result = "orderDetail";
			}
			
		} else {
			result =  "login";	
		}
		
		return result;
	}
	
	/**
	 * 注册
	 * @param model
	 * @param userModel
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/222registerUser.do")
	protected String register(ModelMap model, @ModelAttribute("user") RegisterCommand user,BindingResult bindingResult) throws Exception {
		
		userValidator.validate(user, bindingResult);
		
		UserModel userModel = new UserModel();
		userModel.setUserId(user.getUserId());
		userModel.setPassword(user.getPassword());
		userModel.setName(user.getName());
		userModel.setMailAddress(user.getMailAddress());
		
		// 输入验证
		if (bindingResult.hasErrors()) {
			return "registerUser";
		}
		
		try {
			// 调用注册业务服务
			if (userService.register(userModel)){
				return "login";
			}			
		} catch (UserHasExistException e){
			model.addAttribute("AppException",e.getMessage());
			return "errorPage";	
		}
		return "errorPage";
	}
	
	/**
	 * Logout 登出
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/333logout.do")  
	protected String logout(HttpServletRequest request) throws Exception {
		
		String result = "login";
		
		// session 失效
		request.getSession().invalidate();

		
		return result;
	}	
	
}
